package comoabejas

import javax.mail.internet.MimeMessage
import org.springframework.mail.MailException
import org.springframework.mail.MailSender
import org.springframework.mail.SimpleMailMessage
import org.springframework.mail.javamail.MimeMessageHelper
import com.grailsrocks.authentication.AuthenticationUser
import cr.co.arquetipos.crypto.Blowfish

/*matiaskochman*/
/**
* Hit "http://localhost:8080/ComoAbejas/email?to=me@somewhere.com&subject=hello+world&body=This+is+a+test" to send an email to yourself
*/
class EmailService {
	UserService userService
	MailSender mailSender
	SimpleMailMessage mailMessage // a "prototype" email instance
	MimeMessageHelper mimeMessageHelper
	String blowfishPassword = "tito cosa"
	
	boolean transactional = true
	
	
	
	def sendEmail(String to,String subject,String body){
		def email = [
			to: [ to],        // "to" expects a List, NOT a single email address
			subject: subject,
			text: body         // "text" is the email body
		]
		// sendEmails expects a List
		
		emailService.sendEmails([email])

	}
	
	def sendToUserPurchaseConfirmation(User u){
		def email = [
			to: [ u.email ],        // "to" expects a List, NOT a single email address
			subject: "Como Abejas Baby !!",
			text: "Recien hiciste una compra por Como Abejas, Baby !!"        // "text" is the email body
			  ]
				// sendEmails expects a List
		
		sendEmails([email])

	}
	
	def sendToAllUsersPurchaseConfirmation(Deal deal){
		List<String> emailsList
		List purchases = Purchase.findAll("select p  Purchase p, Deal d where p.deal=:deal ")
		
		for (Purchase p : purchases) {
			emailsList.add p.user.getEmail()
		}
		sendEmails(emailsList)
				
	}
	
	def sendUserConfirmationEmail(Map params){
		
		def email = [
			to: [ params.user.email],        // "to" expects a List, NOT a single email address
			subject: "user confirmation",
			text: getMail(params)
			
		]
		// sendEmails expects a List
		
		sendEmails([email])

	}

	private String getMail(Map params){
		
		String url = "http://localhost:8080/ComoAbejas_f2/email/emailUserConfirmation?password="+params.user.password
		StringBuffer s = new StringBuffer();
		
		s.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">")
		s.append("<html>")
		s.append("<head>")
		s.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />")
		s.append("</head>")
		s.append("<body leftmargin=\"0\" marginwidth=\"0\" topmargin=\"0\" marginheight=\"0\" offset=\"0\">")
		s.append("<center>")
		s.append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" height=\"100%\" width=\"100%\" id=\"backgroundTable\">")
		s.append("<tr>")
		s.append("<td align=\"center\" valign=\"top\">")
		s.append("<a href="+url+"> confirmar usuario </a>")
		s.append("</td>")
		s.append("</tr>")
		s.append("</table>")
		s.append("</centre>")
		s.append("</body>")
		s.append("</html>")
		
		return s.toString()
	}
	
	
	def sendEmails(mails) {
		// Build the mail messages
		
		
		
		def messages = []
		for (mail in mails) {
			// Create a thread safe "sandbox" of the message
			//SimpleMailMessage message = new SimpleMailMessage(mailMessage)
			//SimpleMailMessage message = new SimpleMailMessage()
			MimeMessage message = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			
			//message.to = mail.to
			// use the true flag to indicate you need a multipart message
			helper.setTo(mail.to);
			
			//message.text = mail.text
			// use the true flag to indicate the text included is HTML
			helper.setText(mail.text, true);
			
			message.subject = mail.subject

			
						messages << message
		}
		// Send them all together
		
		
		try {
			//println "about to send ${messages.size()} messages to:n${messages.to.join('n')}"
			//mailSender.send(messages as SimpleMailMessage[])
			mailSender.send(messages as MimeMessage[])
			
		} catch (MailException ex) {
			println "Failed to send emails"
			ex.printStackTrace()
		}
	}
	
	def onConfirmation = {
		
	}
	
	public User emailUserConfirmation(String password){
		AuthenticationUser au = AuthenticationUser.findByPassword(password)
		
		def decryptedPassword = Blowfish.decryptBase64(password, blowfishPassword)
		decryptedPassword.trim()
		
		User u = new User()
		u.setUsername au.getLogin()
		u.setPassword decryptedPassword
		u.setEmail au.getEmail()
		
		User user = userService.saveObj(u)

		return user
	}
}
